import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/homeworks.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/models/student/AssignmentDetail.dart';
import 'package:ichinesereader/models/teacher/assignmentDto.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_date_time_picker/reactive_date_time_picker.dart';
import 'package:reactive_dropdown_search/reactive_dropdown_search.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';

import '../../constants.dart';
import '../../models/book/BookSearchDto.dart';
import '../../widgets/grids/bookGridWithCheckBoxTeaching.dart';

// ignore: must_be_immutable
class HomeworkSteps extends StatefulWidget {
  bool isNew;
  // not use books, use directly from controller
  List<BookItem>? books;
  String? assignmentId;
  AssignmentDetail? assignmentDetail;
  String? from;

  HomeworkSteps(
      {Key? key,
      required this.isNew,
      this.books,
      this.assignmentDetail,
      this.assignmentId,
      this.from})
      : super(key: key);

  @override
  State<HomeworkSteps> createState() => _HomeworkStepsState();
}

class _HomeworkStepsState extends State<HomeworkSteps> {
  int _currentStep = 0;
  int limit = 20;
  final formmodel = new HomeworkFormModel();
  //List<BookItem> _bookItems = [];
  var box = Hive.box('appconfig');
  final SchoolAdminController _controller = Get.find();
  final BooksController _booksController = Get.put(BooksController());
  final HomeworksController _assignmentsController = Get.find();

  List<String> _students = [];
  String classId = '';
  late FormGroup form;
  String title = '';
  String? query;
  BookSearchDto sdto = new BookSearchDto();
  late TextEditingController textController =
      TextEditingController(text: query);
  late TextEditingController completeController =
      TextEditingController(text: '9');

  void _onSubmit() async {
    Log.debug(this.formmodel.form.value);
    if (!form.valid) {
      form.markAllAsTouched();
      return;
    }
    try {
      if (_booksController.selectedLibraryReadingBookItems.length > 0) {
        AssignmentDto dto = new AssignmentDto();
        if (this.formmodel.form.control('settings.allstudents').value != null &&
            this.formmodel.form.control('settings.allstudents').value == true) {
          dto.allStudentInClass = true;
        } else {
          dto.allStudentInClass = false;
          if (this.formmodel.form.control('settings.students').value != null) {
            List<String> _selectedStudents =
                this.formmodel.form.control('settings.students').value;
            if (_selectedStudents.length > 0) {
              List<String> _namelist = [];
              _selectedStudents.forEach((element) {
                int start = element.indexOf(' - ');
                var tempstr = element.substring(0, start);
                _namelist.add(tempstr);
              });
              dto.studentUserNames = _namelist;
            } else {
              dto.studentUserNames = null;
            }
          }
        }
        if (dto.studentUserNames == null && dto.allStudentInClass == false)
          dto.allStudentInClass = true;

        List<String> _bookIds = [];
        _booksController.selectedLibraryReadingBookItems.forEach((element) {
          _bookIds.add(element.bookId.toString());
        });
        dto.bookIds = _bookIds;
        // for edit books
        if (widget.isNew != true) {
          dto.addBookIds = _bookIds;
        }
        dto.extraPoints = this.formmodel.form.control('settings.points').value;
        dto.name = this.formmodel.form.control('settings.name').value;
        var startdate =
            this.formmodel.form.control('settings.startdate').value as DateTime;
        dto.startDate = startdate.millisecondsSinceEpoch;
        dto.createDate = DateTime.now().millisecondsSinceEpoch;
        var enddate =
            this.formmodel.form.control('settings.duedate').value as DateTime;
        dto.endDate = enddate.millisecondsSinceEpoch;

        dto.instruction =
            this.formmodel.form.control('settings.instruction').value;

        if (dto.instruction != '') dto.instructionTrueOrFalse = true;

        dto.numBooks = this.formmodel.form.control('review.totalbooks').value;
        dto.noOfBookToBeRead =
            this.formmodel.form.control('review.completerequired').value;
        dto.settings = new Settings();
        dto.settings?.quizAudio =
            this.formmodel.form.control('features.quizaudioenabled').value;
        dto.settings?.audio = dto.settings?.quizAudio;
        dto.settings?.lang =
            this.formmodel.form.control('features.audiotype').value;
        dto.settings?.language =
            this.formmodel.form.control('features.texttype').value;
        dto.settings?.pinyin =
            this.formmodel.form.control('features.pinyinenabled').value;
        dto.workType = 'ASSIGNMENT';
        _assignmentsController
            .createHomework(classId, dto, widget.assignmentId)
            .then((response) {
          if (response.status == 1000) {
            _booksController.selectedThemedBookItemsClear();
            _booksController.selectedFavoriteReadingBookItemsClear();
            _booksController.selectedLibraryReadingBookItemsClear();
            _booksController.selectedSearchedBookItems.clear();
            Get.snackbar(
                'Message'.tr, 'Homework has been created successfully.'.tr,
                backgroundColor: Theme.of(context).primaryColor,
                colorText: Theme.of(context).primaryColorLight,
                snackPosition: SnackPosition.BOTTOM);
            Get.toNamed('/teacher/homework');
            //Get.back();
          } else {
            Get.snackbar('Message'.tr, 'Failed to create homework.'.tr,
                backgroundColor: Theme.of(context).primaryColor,
                colorText: Theme.of(context).primaryColorLight,
                snackPosition: SnackPosition.BOTTOM);
          }
        });
      }
    } catch (error) {
      Get.snackbar('Message'.tr, 'Failed to create homework.'.tr,
          backgroundColor: Theme.of(context).primaryColor,
          colorText: Theme.of(context).primaryColorLight,
          snackPosition: SnackPosition.BOTTOM);
      Log.debug(error);
    }
  }

  cancel() {
    if (_currentStep > 0) setState(() => _currentStep -= 1);
  }

  continued() {
    if (_currentStep == 0) {
      if (!form.valid) {
        form.markAllAsTouched();
        return;
      }
    }
    if (_currentStep == 2) {
      if (this.formmodel.form.valid)
        _onSubmit();
      else {
        Log.debug(this.formmodel.form.value);
        this.formmodel.form.markAllAsTouched();
      }
    }
    if (_currentStep < 2) setState(() => _currentStep += 1);
  }

  tapped(int step) {
    setState(() => _currentStep = step);
  }

  Timer searchOnStoppedTyping = Timer.periodic(
    const Duration(seconds: 1000),
    (timer) {},
  );
  void _onChangeHandler(value) {
    const duration = Duration(milliseconds: 1000);
    // set the duration that you want call search() after that.
    setState(() => searchOnStoppedTyping.cancel());
    setState(() => searchOnStoppedTyping =
        new Timer(duration, () => _handleSearchText(value)));
  }

  void _handleSearchText(value) {
    sdto.query = value;
    _booksController.setBookSearchDto(sdto);
    Log.debug(sdto);
    _booksController.fetchSearchOpenLibraryBookItems(20, 0, sdto);
  }

  void clearText() {
    textController.clear();
    sdto.query = null;
    _booksController.setBookSearchDto(sdto);
    _booksController.fetchSearchOpenLibraryBookItems(20, 0, sdto);
  }

  @override
  void initState() {
    classId = box.get(CacheManagerKey['currentclass'].toString());
    if (classId != '') _controller.fetchClassDetailsNewByClassId(classId);
    // clear the search query when come again
    _booksController.setBookSearchDto(sdto);
    _booksController.fetchOpenReadingItems(limit, 0);
    // set books
    widget.books!.forEach((book) {
      _booksController.addAssignedToSelectedBookItems(
          book, NanhaiBookReadingTypes.library);
    });
    form = formmodel.form;
    if (widget.isNew == true && widget.books != null) {
      title = 'Create Homework'.tr;
      form.control('settings.allstudents').value = true;
      form.control('review.totalbooks').value =
          _booksController.selectedLibraryReadingBookItems.length;
      form.control('review.completerequired').value = widget.books?.length;
      form
          .control('review.completerequired')
          .setAsyncValidators([_asyncCheckBookNumber]);
    } else {
      title = 'Edit Homework'.tr;
      var assignment = widget.assignmentDetail;
      form.control('settings.allstudents').value =
          assignment?.allStudentInClass ?? false;
      form.control('settings.name').value = assignment?.name;
      //if (widget.from == 'edit') {
      form.control('settings.startdate').value =
          new DateTime.fromMillisecondsSinceEpoch(assignment?.startDate as int);
      form.control('settings.duedate').value =
          new DateTime.fromMillisecondsSinceEpoch(assignment?.endDate as int);
      //}
      form.control('settings.points').value = assignment?.extraPoints;
      form.control('settings.instruction').value = assignment?.instruction;
      form
          .control('review.completerequired')
          .setAsyncValidators([_asyncCheckBookNumber]);

      List<String> usernames = [];
      if (assignment?.studentMiniJsoNs != null) {
        assignment?.studentMiniJsoNs?.forEach((ministudent) {
          usernames.add(
              '${ministudent.userName} - ${ministudent.firstName} ${ministudent.lastName}');
        });
      }
      form.control('settings.students').value = usernames;
      form.control('features.quizaudioenabled').value =
          assignment?.settings?.audio;
      form.control('features.pinyinenabled').value =
          assignment?.settings?.pinyin;
      form.control('features.texttype').value = assignment?.settings?.language;
      form.control('features.audiotype').value = assignment?.settings?.lang;
      form.control('review.totalbooks').value =
          _booksController.selectedLibraryReadingBookItems.length;
      form.control('review.completerequired').value =
          _booksController.selectedLibraryReadingBookItems.length;
    }
    //sdto = _booksController.getBookSearchDeto();
    // if (sdto.query != null) {
    //  query = sdto.query;
    // } else {
    //   query = '';
    // }

    super.initState();
  }

  @override
  dispose() {
    super.dispose();
  }

  // // reduce the book count for total and complete
  // void _handleRemoveChanged() {
  //   form = formmodel.form;
  //   form.control('review.totalbooks').value =
  //       _booksController.selectedLibraryReadingBookItems.length;
  //   form.control('review.completerequired').value =
  //       _booksController.selectedLibraryReadingBookItems.length;
  // }

  Future<Map<String, dynamic>?> _asyncCheckBookNumber(
      AbstractControl<dynamic> control) async {
    final error = {
      'exceed':
          'Homework complete requirement cannot be greater than assigned books!'
    };
    int completedNum = control.value;
    if (completedNum >
        _booksController.selectedLibraryReadingBookItems.length) {
      control.markAsTouched();
      return error;
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build teacher homwork StepsState');
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
          title: Text(title),
          leading: BackButton(onPressed: () {
            // clear select in here, otherwize duplicate books when not submit
            _booksController.selectedThemedBookItemsClear();
            _booksController.selectedFavoriteReadingBookItemsClear();
            _booksController.selectedLibraryReadingBookItemsClear();
            _booksController.selectedSearchedBookItems.clear();
            Navigator.of(context).pop();
          })),
      body: Stepper(
        currentStep: _currentStep,
        physics: ScrollPhysics(),
        onStepTapped: (step) => tapped(step),
        //Customising the Stepper controls
        controlsBuilder: (BuildContext context, ControlsDetails controls) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                ElevatedButton(
                  onPressed: controls.onStepContinue!,
                  child: Text('NEXT'.tr),
                ),
                if (_currentStep != 0)
                  TextButton(
                    onPressed: controls.onStepCancel,
                    child: Text(
                      'BACK'.tr,
                      style: TextStyle(color: Color.fromARGB(255, 97, 96, 96)),
                    ),
                  ),
              ],
            ),
          );
        },
        onStepContinue: continued,
        onStepCancel: cancel,
        type: (GetPlatform.isAndroid || GetPlatform.isIOS)
            ? StepperType.vertical
            : StepperType.horizontal,
        steps: [
          Step(
            title: Text('Settings'.tr),
            isActive: _currentStep >= 0,
            state: _currentStep >= 0 ? StepState.complete : StepState.disabled,
            content: Obx(() {
              if (_controller.classDetailsNew.value.studentResps != null &&
                  _controller.classDetailsNew.value.studentResps!.isNotEmpty) {
                _students.clear();
                //_userNames.clear();
                for (int i = 0;
                    i < _controller.classDetailsNew.value.studentResps!.length;
                    i++) {
                  var usernamestring = _controller
                          .classDetailsNew.value.studentResps![i].userName
                          .toString() +
                      ' - ' +
                      _controller
                          .classDetailsNew.value.studentResps![i].firstName
                          .toString() +
                      ' ' +
                      _controller
                          .classDetailsNew.value.studentResps![i].lastName
                          .toString();
                  _students.add(usernamestring);
                }
                return Padding(
                  padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
                  child: ReactiveForm(
                    formGroup: form,
                    child: Column(
                      children: <Widget>[
                        ReactiveTextField(
                          formControlName: 'settings.name',
                          textInputAction: TextInputAction.next,
                          style: Theme.of(context).textTheme.titleSmall,
                          onSubmitted: (_) => form.focus('settings.students'),
                          decoration: InputDecoration(
                            labelText: '*Task Name'.tr,
                          ),
                          validationMessages: {
                            ValidationMessage.required: (_) =>
                                'The task name must not be empty'.tr
                          },
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveCheckboxListTile(
                          formControlName: 'settings.allstudents',
                          title: Text(
                            'All Students?'.tr,
                            style: Theme.of(context).textTheme.titleSmall,
                          ),
                          subtitle: Text(
                              'If selected, task will be assigned to all students in the class.'
                                  .tr),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveValueListenableBuilder<bool>(
                          formControlName: 'settings.allstudents',
                          builder: (context, control, child) {
                            return Visibility(
                                visible: !(control.value ?? false),
                                child: Column(
                                  children: [
                                    ReactiveDropdownSearchMultiSelection<String,
                                        String>(
                                      formControlName: 'settings.students',
                                      dropdownDecoratorProps:
                                          DropDownDecoratorProps(
                                        dropdownSearchDecoration:
                                            InputDecoration(
                                          hintText: "Select students".tr,
                                          labelText: "Students".tr,
                                        ),
                                      ),
                                      popupProps: PopupPropsMultiSelection.menu(
                                          showSelectedItems: true,
                                          showSearchBox: true),
                                      items: _students,
                                      showClearButton: true,
                                    ),
                                    SizedBox(
                                      height: 12,
                                    ),
                                  ],
                                ));
                          },
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveDateTimePicker(
                          formControlName: 'settings.startdate',
                          firstDate: DateTime.now(),
                          lastDate: DateTime.now().add(Duration(days: 365)),
                          type: ReactiveDatePickerFieldType.dateTime,
                          style: Theme.of(context).textTheme.titleSmall,
                          decoration: InputDecoration(
                            labelText: 'Start Date'.tr,
                            border: OutlineInputBorder(),
                            helperText: '',
                            suffixIcon: Icon(Icons.calendar_today),
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveDateTimePicker(
                          formControlName: 'settings.duedate',
                          firstDate: DateTime.now(),
                          lastDate: DateTime.now().add(Duration(days: 365)),
                          style: Theme.of(context).textTheme.titleSmall,
                          type: ReactiveDatePickerFieldType.dateTime,
                          decoration: InputDecoration(
                            labelText: 'Due Date'.tr,
                            border: OutlineInputBorder(),
                            helperText: '',
                            suffixIcon: Icon(Icons.calendar_today),
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveTextField(
                          formControlName: 'settings.points',
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly
                          ],
                          // Only numbers can be entered
                          textInputAction: TextInputAction.next,
                          style: Theme.of(context).textTheme.titleSmall,
                          onSubmitted: (_) =>
                              form.focus('settings.instruction'),
                          decoration: InputDecoration(
                            labelText: 'Points'.tr,
                            helperText:
                                'Students will get these points when they complete the assignment.'
                                    .tr,
                          ),
                          validationMessages: {
                            ValidationMessage.max: (_) =>
                                'Extra Points Range 0 - 5000'.tr
                          },
                        ),
                        SizedBox(
                          height: 18,
                        ),
                        ReactiveTextField(
                          formControlName: 'settings.instruction',
                          maxLines: 3,
                          textInputAction: TextInputAction.next,
                          style: Theme.of(context).textTheme.titleSmall,
                          decoration: InputDecoration(
                            alignLabelWithHint: true,
                            labelText: 'Instructions'.tr,
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveSegmentedControl<String, String>(
                          formControlName: 'features.audiotype',
                          decoration: InputDecoration(
                            labelText: 'Audio'.tr,
                            border: OutlineInputBorder(),
                            helperText: '',
                          ),
                          padding: const EdgeInsets.all(0),
                          unselectedColor: Get.theme.primaryColorLight,
                          children: {
                            'Mandarin': Text('Mandarin'.tr,
                                style: TextStyle(
                                  color: Color(0xff00599b),
                                  fontSize: 16.0,
                                  letterSpacing: 1.0,
                                )),
                            'Cantonese': Text('Cantonese'.tr,
                                style: TextStyle(
                                  color: Color(0xff00599b),
                                  fontSize: 16.0,
                                  letterSpacing: 1.0,
                                )),
                            'No_audio': Text('No Audio'.tr,
                                style: TextStyle(
                                  color: Color(0xff00599b),
                                  fontSize: 16.0,
                                  letterSpacing: 1.0,
                                )),
                          },
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveSwitchListTile(
                          title: Text(
                            'Pinyin'.tr,
                            style: Theme.of(context).textTheme.titleSmall,
                          ),
                          subtitle: Text(
                              'When text option set to NO TEXT, pinyin can not be displayed.'
                                  .tr),
                          formControlName: 'features.pinyinenabled',
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveSegmentedControl<String, String>(
                          formControlName: 'features.texttype',
                          decoration: InputDecoration(
                            labelText: 'Text'.tr,
                            border: OutlineInputBorder(),
                            helperText: '',
                          ),
                          padding: const EdgeInsets.all(0),
                          unselectedColor: Get.theme.primaryColorLight,
                          children: {
                            'Simplified': Text('Simplified'.tr,
                                style: TextStyle(
                                  color: Color(0xff00599b),
                                  fontSize: 16.0,
                                  letterSpacing: 1.0,
                                )),
                            'Traditional': Text('Traditional'.tr,
                                style: TextStyle(
                                  color: Color(0xff00599b),
                                  fontSize: 16.0,
                                  letterSpacing: 1.0,
                                )),
                            'No text': Text('No Text'.tr,
                                style: TextStyle(
                                  color: Color(0xff00599b),
                                  fontSize: 16.0,
                                  letterSpacing: 1.0,
                                )),
                          },
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        ReactiveSwitchListTile(
                          title: Text(
                            'Quiz Audio'.tr,
                            style: Theme.of(context).textTheme.titleSmall,
                          ),
                          subtitle: Text(
                              'When enabled and audio option set to NO AUDIO, quiz will be played in Mandarin.'
                                  .tr),
                          formControlName: 'features.quizaudioenabled',
                        ),
                      ],
                    ),
                  ),
                );
              } else {
                return Text('');
              }
            }),
          ),
          Step(
              title: Text('Books'.tr),
              isActive: _currentStep >= 0,
              state:
                  _currentStep >= 1 ? StepState.complete : StepState.disabled,
              content: ReactiveForm(
                formGroup: form,
                child: Column(
                  children: <Widget>[
                    _booksController.obx(
                      (data) => FormBuilderChoiceChip(
                        decoration: InputDecoration(
                            labelText: '', border: InputBorder.none),
                        name: 'subprogram_choice_chip',
                        onChanged: (value) {
                          var item = value as BookItem;
                          _booksController.removeAssignedFromSelectedBookItems(
                              item, NanhaiBookReadingTypes.library, form);
                          //_handleRemoveChanged();
                        },
                        options:
                            _booksController.selectedLibraryReadingBookItems
                                .map((item) => FormBuilderChipOption<BookItem>(
                                      value: item,
                                      child: RichText(
                                        text: TextSpan(
                                          children: [
                                            TextSpan(
                                              text:
                                                  '${item.bookTitle.toString()} \u{274c}',
                                              style: TextStyle(
                                                color: Colors.black,
                                                fontSize: 15,
                                                letterSpacing: 0,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ))
                                .toList(),
                      ),
                    ),
                    ReactiveTextField(
                      formControlName: 'review.totalbooks',
                      keyboardType: TextInputType.number,
                      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                      // Only numbers can be entered
                      textInputAction: TextInputAction.next,
                      style: Theme.of(context).textTheme.titleSmall,
                      readOnly: true,
                      onSubmitted: (_) => form.focus('review.completerequired'),
                      decoration: InputDecoration(
                        labelText: 'Books assigned'.tr,
                        helperText: '',
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveTextField(
                      formControlName: 'review.completerequired',
                      keyboardType: TextInputType.number,
                      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                      // Only numbers can be entered
                      textInputAction: TextInputAction.next,
                      style: Theme.of(context).textTheme.titleSmall,
                      decoration: InputDecoration(
                        labelText: 'Complete required'.tr,
                        helperText: '',
                      ),
                      validationMessages: {
                        'exceed': (_) =>
                            'Homework complete requirement cannot be greater than assigned books!'
                                .tr
                      },
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Container(
                      width: 600,
                      child: TextFormField(
                        onChanged: (text) {
                          //_handleSearchText(textController.text);
                          _onChangeHandler(textController.text);
                        },
                        controller: textController,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.search),
                          suffixIcon: IconButton(
                            icon: Icon(Icons.clear),
                            onPressed: () {
                              clearText();
                            },
                          ),
                          hintText: 'Search Book...'.tr,
                          border: OutlineInputBorder(),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Container(
                        height: 400,
                        child: Column(
                          children: [
                            Flexible(
                              child: Center(
                                child: _booksController.obx(
                                  (data) => BookGridWithCheckBoxTeaching(
                                      books: _booksController
                                          .openLibraryReadingBookItems,
                                      readingType:
                                          NanhaiBookReadingTypes.library,
                                      form: form),
                                  onEmpty: Text('Books not available'.tr),
                                ),
                              ),
                            ),
                          ],
                        ))
                  ],
                ),
              )),
          Step(
            title: Text('Review'.tr),
            isActive: _currentStep >= 0,
            state: _currentStep >= 2 ? StepState.complete : StepState.disabled,
            content: Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: ReactiveForm(
                formGroup: form,
                child: Column(
                  children: <Widget>[
                    ReactiveTextField(
                      formControlName: 'settings.name',
                      textInputAction: TextInputAction.next,
                      style: Theme.of(context).textTheme.titleSmall,
                      onSubmitted: (_) => form.focus('settings.students'),
                      decoration: InputDecoration(
                        labelText: 'Task Name'.tr,
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveCheckboxListTile(
                      formControlName: 'settings.allstudents',
                      title: Text(
                        'All Students?'.tr,
                        style: Theme.of(context).textTheme.titleSmall,
                      ),
                      // subtitle: Text(
                      //     'If selected, task will be assigned to all students in the class.'
                      //         .tr),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveValueListenableBuilder<bool>(
                      formControlName: 'settings.allstudents',
                      builder: (context, control, child) {
                        return Visibility(
                            visible: !(control.value ?? false),
                            child: Column(
                              children: [
                                ReactiveDropdownSearchMultiSelection<String,
                                    String>(
                                  formControlName: 'settings.students',
                                  dropdownDecoratorProps:
                                      DropDownDecoratorProps(
                                    dropdownSearchDecoration: InputDecoration(
                                      hintText: "Select students".tr,
                                      labelText: "Students".tr,
                                    ),
                                  ),
                                  popupProps: PopupPropsMultiSelection.menu(
                                      showSelectedItems: true,
                                      showSearchBox: true),
                                  items: _students,
                                  showClearButton: true,
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                              ],
                            ));
                      },
                    ),
                    // if (form.control('settings.students').value != null)
                    //   ReactiveDropdownSearchMultiSelection<String, String>(
                    //     formControlName: 'settings.students',
                    //     // dropdownSearchBaseStyle:
                    //     //    Theme.of(context).textTheme.titleSmall,
                    //     dropdownDecoratorProps: DropDownDecoratorProps(
                    //       dropdownSearchDecoration: InputDecoration(
                    //         hintText: "Select students".tr,
                    //         labelText: "Students".tr,
                    //       ),
                    //     ),
                    //     //popupBackgroundColor: Colors.white,
                    //     popupProps: PopupPropsMultiSelection.menu(
                    //         showSelectedItems: true, showSearchBox: true),
                    //     //mode: Mode.MENU,
                    //     ////hint: "Select Students",
                    //     //showSelectedItems: true,
                    //     items: form.control('settings.students').value,
                    //     // label: "Select Students",
                    //     showClearButton: true,
                    //     // showSearchBox: true,
                    //   ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveDateTimePicker(
                      formControlName: 'settings.startdate',
                      firstDate: DateTime.now(),
                      lastDate: DateTime.now().add(Duration(days: 365)),
                      type: ReactiveDatePickerFieldType.dateTime,
                      style: Theme.of(context).textTheme.titleSmall,
                      decoration: InputDecoration(
                        labelText: 'Start Date'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                        suffixIcon: Icon(Icons.calendar_today),
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveDateTimePicker(
                      formControlName: 'settings.duedate',
                      firstDate: DateTime.now(),
                      lastDate: DateTime.now().add(Duration(days: 365)),
                      style: Theme.of(context).textTheme.titleSmall,
                      type: ReactiveDatePickerFieldType.dateTime,
                      decoration: InputDecoration(
                        labelText: 'Due Date'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                        suffixIcon: Icon(Icons.calendar_today),
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveTextField(
                      formControlName: 'settings.points',
                      keyboardType: TextInputType.number,
                      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                      // Only numbers can be entered
                      textInputAction: TextInputAction.next,
                      style: Theme.of(context).textTheme.titleSmall,
                      onSubmitted: (_) => form.focus('settings.instruction'),
                      decoration: InputDecoration(
                        labelText: 'Points'.tr,
                        helperText:
                            'Students will get these points when they complete the homework.'
                                .tr,
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveTextField(
                      formControlName: 'settings.instruction',
                      maxLines: 3,
                      textInputAction: TextInputAction.next,
                      style: Theme.of(context).textTheme.titleSmall,
                      decoration: InputDecoration(
                        alignLabelWithHint: true,
                        labelText: 'Instructions'.tr,
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveSegmentedControl<String, String>(
                      formControlName: 'features.audiotype',
                      decoration: InputDecoration(
                        labelText: 'Audio'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                      ),
                      padding: const EdgeInsets.all(0),
                      unselectedColor: Get.theme.primaryColorLight,
                      children: {
                        'Mandarin': Text('Mandarin'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                        'Cantonese': Text('Cantonese'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                        'No_audio': Text('No Audio'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                      },
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveSwitchListTile(
                      title: Text(
                        'Pinyin'.tr,
                        style: Theme.of(context).textTheme.titleSmall,
                      ),
                      subtitle: Text(
                          'When text option set to NO TEXT, pinyin can not be displayed.'
                              .tr),
                      formControlName: 'features.pinyinenabled',
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveSegmentedControl<String, String>(
                      formControlName: 'features.texttype',
                      decoration: InputDecoration(
                        labelText: 'Text'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                      ),
                      padding: const EdgeInsets.all(0),
                      unselectedColor: Get.theme.primaryColorLight,
                      children: {
                        'Simplified': Text('Simplified'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                        'Traditional': Text('Traditional'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                        'No text': Text('No Text'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                      },
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveSwitchListTile(
                      title: Text(
                        'Quiz Audio'.tr,
                        style: Theme.of(context).textTheme.titleSmall,
                      ),
                      subtitle: Text(
                          'When enabled and audio option set to NO AUDIO, quiz will be played in Mandarin.'
                              .tr),
                      formControlName: 'features.quizaudioenabled',
                    ),
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
